<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 消息提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center="">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧Tab栏 -->
      <!-- label-position	表单域标签的位置 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" class="demo-ruleForm">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="getData">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <!-- type="number"限制输入的类型必须为数字型 -->
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 商品分类的级联选择器 -->
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cascaderProps"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 商品参数面板的绘制 -->
            <el-form-item :label="item.attr_name" v-for="(item, i) in goods_params" :key="i">
              <el-checkbox-group v-model="item.attr_vals" v-for="(cb, index) in item.attr_vals" :key="index">
                <el-checkbox :label="cb" border size="small" style="float: left;"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 商品属性面板的绘制 -->
            <el-form-item :label="item.attr_name" v-for="(item, i) in staticPro" :key="i">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload class="upload-demo" :action="uploadURL" :headers="headerObj" :on-preview="handlePreview"
              :on-remove="handleRemove" list-type="picture" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本内容 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加按钮 -->
            <el-button type="primary" @click="addGoods" style="margin: 15px; float: right">添加按钮</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 预览对话框 -->
      <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="30%">
        <img :src="pictureUrl" alt="" style="width:100%">
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
// 导入深拷贝包
import _ from 'lodash'
export default {
  data() {
    return {
      // 激活项
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 被选择的id数组,相当于之前的selectedKeys
        goods_cat: [],
        pics: [],
        // 商品介绍
        goods_introduce: '',
        attrs: []

      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' },],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' },],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' },],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' },]
      },
      // 分类列表数据
      cateList: [],
      // 级联选择器props配置项
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数
      goods_params: [],
      // 静态属性
      staticPro: [],
      // 上传图片路径
      uploadURL: 'http://47.108.251.106:8881/api/private/v1/upload',
      // 上传图片请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      // 图片地址
      pictureUrl: '',
      // 预览对话框状态
      previewDialogVisible: false,

    }
  },
  methods: {
    // 获取分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories');
      // console.log(res)
      if (res.meta.status !== 200) return this.$msg.error("获取商品分类列表失败");
      this.cateList = res.data;
    },
    // 监听级联选择器变化
    handleChange() {
      // console.log(this.addForm.goods_cat);
      // 限制只能选择第三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // 控制Tab栏的切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName = '0' && this.addForm.goods_cat.length !== 3) {
        this.$msg.error("请选择商品分类");
      }
    },
    // 获取商品动态参数
    async getData() {
      if (this.activeIndex === '1') {
        // 获取动态参数
        const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/attributes`, { params: { sel: 'many' } });
        // console.log(res)
        if (res.meta.status !== 200) return this.$msg.error("获取商品参数失败");
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
        })
        this.goods_params = res.data;
        // console.log(this.goods_params)

      }
      // 获取静态属性
      else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/attributes`, { params: { sel: 'only' } });
        // console.log(res)
        if (res.meta.status !== 200) return this.$msg.error("获取商品参数失败");
        this.staticPro = res.data;
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      // console.log(file)
      this.pictureUrl = file.response.data.url;
      // console.log(this.pictureUrl)
      this.previewDialogVisible = true;
    },
    // 移除图片
    handleRemove(file) {
      // console.log(file)
      const filePath = file.response.data.tem_path;
      const i = this.addForm.pics.findIndex(x => x.pic === filePath);
      // console.log(i)
      this.addForm.pics.splice(i, 1);


    },
    // 上传成功后的操作
    handleSuccess(res) {
      // console.log(res)
      const picInfo = { "pic": res.data.tmp_path };
      this.addForm.pics.push(picInfo);
      // console.log(this.addForm)
    },
    // 添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$msg.error("请填写必要的表单项");
        // 执行添加的业务逻辑
        // 将分类数组变为字符串形式，但级联选择器需要的是数组
        //所以这里采用深拷贝
        // this.addForm.goods_cat = JSON.parse(JSON.stringify(this.addForm.goods_cat));
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(',');
        // 动态参数,attr_vals改为字符串类型
        this.goods_params.forEach(item => {
          const activeParams = { attr_id: item.attr_id, attr_value: item.attr_vals.join('') };
          this.addForm.attrs.push(activeParams);
        })
        // 静态属性
        this.staticPro.forEach(item => {
          const static_pro = { "attr_id": item.attr_id, "attr_value": item.attr_vals };
          this.addForm.attrs.push(static_pro);
        })
        form.attrs = this.addForm.attrs;
        // console.log(form)
        // 发起请求添加数据
        const { data: res } = await this.$http.post('goods', form);
        console.log(res)
        if (res.meta.status !== 201) return this.$msg.error("添加商品失败");
        this.$msg.success("添加商品成功");
        this.$router.push('/goods');

      })

    }
  },
  created() {
    this.getCateList();
  }

}
</script>

<style lang="less" scoped>
.el-input,
.el-cascader {
  float: left;
  width: 500px;
}
</style>